package cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.slf4j.Logger;

import cn.ilikes.tools.logs.Loggerfactory;
import cn.ilikes.tools.nosql.jpa.SysConfigs;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.ABIndexSource;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools.AsySingLuceneService;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools.AsyZookeeprLockFactory;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools.AsyZookeeprLockListener;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools.IAsyLuceneService;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools.ZookeeprLockFactory;
import cn.ilikes.tools.nosql.jpa.clients.indexs.index.lucenes.asytools.ZookeeprLockListener;
import cn.ilikes.tools.nosql.jpa.metadatas.EntityMetaData;

/**
 * 异步
 * 
 * @author fack
 * 
 */
public class AsyLuceneClientIndex extends LuceneClientIndex implements ZookeeprLockListener {

	private Logger logger = Loggerfactory.instance(AsyLuceneClientIndex.class);

	private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

	private IAsyLuceneService asyLuceneService;

	private ZookeeprLockFactory zookeeprLockFactory;

	private String localId;

	private String lockNode;

	public AsyLuceneClientIndex(ABIndexSource indexSource) {
		super(indexSource);
		asyLuceneService = AsySingLuceneService.instance(indexSource, createAnalyzer());
		localId = System.currentTimeMillis() + "oooo";
		lockNode = indexSource.getIndexConfigs().getProperties().getProperty(SysConfigs.index_zookeeper_lock_node);
		Loggerfactory.print("this AsyLuceneClientIndex " + this.toString());
		zookeeprLockFactory = new AsyZookeeprLockFactory(indexSource.getIndexConfigs(), new AsyZookeeprLockListener(lockNode, localId, this));

	}

	@Override
	protected IndexReader createIndexReader() {

		return asyLuceneService.createIndexReader();
	}

	@Override
	protected IndexSearcher createIndexSearcher() {

		return asyLuceneService.createIndexSearcher();
	}

	@Override
	protected IndexWriter createIndexWriter() {

		return asyLuceneService.createIndexWriter();
	}

	@Override
	protected void wirteDocument(EntityMetaData metadata, Document document, Object entity, IndexAction indexAction) {
		if (Loggerfactory.isdebug(logger))
			Loggerfactory.debug(logger, "Indexing document: " + document + " for in file system using Lucene");

		//			try 
		//			{
		switch (indexAction) {
		case insert:
			if (Loggerfactory.isdebug(logger))
				Loggerfactory.debug(logger, "Lucene indexing insert : " + entity.toString());
			asyLuceneService.wirte(document);
			break;
		case update: {
			//					Term trem = new Term(IClientIndex.JPA_SQL_ID_FIELD, LuceneQueryUtils.getJPAHBaseKeyofEntity(metadata, entity));
			//					if (Loggerfactory.isdebug(logger))
			//						Loggerfactory.debug(logger, "Lucene indexing update  : " + LuceneQueryUtils.getJPAHBaseKeyofEntity(metadata, entity));
			//					indexWriter.updateDocument(trem, document);
		}
			break;

		default:
			break;
		}

		//			} catch (CorruptIndexException e) {
		//				Loggerfactory.error(logger, "Error while indexing document " + document + " into Lucene. Details:" + e.getMessage());
		//				throw new ClientIndexingRunTimeException("Error while indexing document " + document + " into Lucene.", e);
		//			} catch (IOException e) {
		//				Loggerfactory.error(logger, "Error while indexing document " + document + " into Lucene. Details:" + e.getMessage());
		//				e.printStackTrace();
		//				throw new ClientIndexingRunTimeException("Error while indexing document " + document + " into Lucene.", e);
		//			}

	}

	@Override
	protected void removeDocument(Term term, IndexAction indexAction) {

	}

	@Override
	public void lock(String parents, String path) {
		System.out.println("======================lock");
		try {
			asyLuceneService.merg();
		} finally {
			zookeeprLockFactory.unLock(parents, path);
		}
	}

	@Override
	public void init() {
		zookeeprLockFactory.start();
		asyLuceneService.init();
		asyLuceneService.merg();
		
		service.scheduleWithFixedDelay(new Runnable() {
			@Override
			public void run() {
				System.out.println("======================================= 1111111111111111");
				if (Loggerfactory.isdebug(logger))
					Loggerfactory.debug(logger, "addLock .................................... ");
				zookeeprLockFactory.addLock(localId, Long.toString(System.currentTimeMillis()));
			}
		}, 0, 5, TimeUnit.SECONDS);

	}

	@Override
	public void close() {
		asyLuceneService.close();

	}

	@Override
	public void flush() {

	}

	@Override
	public boolean isOpen() {

		return false;
	}

	@Override
	public void rollback() {

	}

	@Override
	protected Analyzer createAnalyzer() {
		return null;
	}

}
